package com.zaprit.search.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @author Dell
 */
@Controller
public class FileUploadController
{

	private static final String	FAILURE		= "0";
	private static final String	SUCCESS		= "1";
	private static final String	destination	= System.getProperty("java.io.tmpdir", "/temp");

	/**
	 * @param attachmentId
	 * @param multipartHttpServletRequest
	 * @param response
	 * @return 1 for success and 0 for failure
	 */
	@RequestMapping(value = "file/upload/{attachmentId}", method = RequestMethod.POST)
	public String uploadFile(@PathVariable("attachmentId") String attachmentId, MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse response)
	{
		String fileName = null;
		try
		{
			Iterator<String> itr = multipartHttpServletRequest.getFileNames();
			MultipartFile multipartFile = multipartHttpServletRequest.getFile(itr.next());

			if (multipartFile != null)
			{
				fileName = multipartFile.getOriginalFilename();
				multipartFile.transferTo(new File(destination));
			}
			response.getWriter().write(fileName != null ? SUCCESS : FAILURE);
			response.flushBuffer();
		}
		catch (IllegalStateException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
